package com.wu.company.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * created by wuyanshen on 2017/12/19 1:02
 */
@Component
public class WebFailHandler extends SimpleUrlAuthenticationFailureHandler {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper mapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.info("登录失败！");
       /* response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());//服务器内部异常（也就是500错误）
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(mapper.writeValueAsString(exception));*/
//       super.onAuthenticationFailure(request,response,exception);
        String msg = "";
        if(exception.getMessage().equals("User is disabled")){
             msg = "您的账户已被锁定，请联系管理员";
        }else{
             msg = "您的账户或密码错误";
        }
        HttpSession session = request.getSession();
        session.removeAttribute("msg");
        session.setAttribute("msg",msg);
        String targetUrl = "/login/login.jsp";
        getRedirectStrategy().sendRedirect(request, response, targetUrl);

    }
}
